// 异步loading
export const AsyncShowLoading = (title: string): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: title,
      success: (res) => {
        if (res.errMsg === 'showLoading:ok') {
          resolve(true);
        } else {
          reject('打开失败')
        }
      },
      fail: () => {
        reject('打开失败')
      },
    });
  });
}

// 异步关闭loading
export const AsyncHideLoading = (): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    wx.hideLoading({
      success: (res) => {
        if (res.errMsg === 'hideLoading:ok') {
          resolve(true);
        } else {
          reject('关闭失败')
        }
      },
      fail: () => {
        reject('关闭失败')
      },
    });
  });
}

// 异步打开toast
export const AsyncShowToast = (title: string = '提示', duration: number = 2500): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    wx.showToast({
      title,
      duration,
      success: (res) => {
        if (res.errMsg === 'showToast:ok') {
          resolve(true);
        } else {
          reject('打开失败')
        }
      },
      fail: () => {
        reject('打开失败')
      },
    });
  });
}

// 异步关闭toast
export const AsyncHideToast = (): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    wx.hideToast({
      success: (res) => {
        if (res.errMsg === 'hideToast:ok') {
          resolve(true);
        } else {
          reject('关闭失败');
        }
      },
      fail: () => {
        reject('关闭失败');
      },
    });
  });
}

/**
 * 计算图片md5值
 * @param {*} filePath 需要为抖音地址
 */
export const GetMD5 = (filePath: string): Promise<string> => {
  return new Promise((resolve, reject) => {
    wx.getFileSystemManager().getFileInfo({
      filePath,
      digestAlgorithm: "md5",
      success: (data) => {
        if (data.errMsg === 'getFileInfo:ok' && data.digest) {
          resolve(data.digest);
        } else {
          reject('md5获取失败')
        }
      },
      fail: () => {
        reject('md5获取失败')
      },
    })
  })
}

/**
 * 获取Storage
 * @param key key
 * @description 这里不使用reject返回boolean用以判定
 */
export const GetLocal = (key: string): Promise<any> => {
  return new Promise((resolve) => {
    wx.getStorage({
      key,
      success: (res) => {
        console.log('GetLocal', res)
        if (res.errMsg === 'getStorage:ok') {
          resolve(res.data);
        } else {
          resolve('');
        }
      },
      fail: () => {
        resolve('');
      }
    })
  });
}

// 设置Storage
export const SetLocal = (key: string, value: any): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    wx.setStorage({
      key,
      data: value,
      success: (res) => {
        if (res.errMsg === 'setStorage:ok') {
          resolve(true);
        } else {
          reject('保存失败');
        }
      },
      fail: () => {
        reject('保存失败');
      }
    })
  });
}

/**
 * 打开模态弹出框
 * @param {*} title 标题
 * @param {*} content 内容
 * @param {*} showCancel 是否显示取消按钮
 */
export const OpenModal = (
  title: string = '提示',
  content: string = '',
  showCancel: boolean = true,
): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    wx.showModal({
      title: title,
      content: content,
      showCancel,
      success: (res) => {
        if (res.errMsg === 'showModal:ok') {
          resolve(true);
        } else {
          reject('弹窗失败');
        }
      },
      fail: () => {
        reject('弹窗失败');
      },
    });
  })
}

// 获取权限，例如："scope.camera"
export const GetAuth = (authName: string): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success: (res: any): void => {
        if (res.errMsg === 'getSetting:ok') {
          let _allowed = res.authSetting[`scope.${authName}`];
          if (_allowed) {
            resolve(true);
          } else {
            resolve(false);
          }
        } else {
          reject('获取权限失败');
        }
      },
      fail: () => {
        reject('获取权限失败');
      },
    });
  })
}

// 打开设置页面
export const OpenSetting = (): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    wx.openSetting({
      success: (res) => {
        if (res.errMsg === 'openSetting:ok') {
          resolve(true);
        } else {
          reject('设置打开失败');
        }
      },
      fail: () => {
        reject('设置打开失败');
      },
    });
  })
}

// 跳转页面
export const ToPage = (url: string): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    wx.navigateTo({
      url,
      success: () => {
        resolve(true);
      },
      fail: (error) => {
        console.log('navigateTo', error)
        reject('跳转页面失败');
      }
    });
  });
}

// 刷新当前页
export const RedirectTo = (url: string): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    wx.redirectTo({
      url: url,
      success(res) {
        if (res.errMsg === 'redirectTo:ok') {
          resolve(true)
        } else {
          reject('刷新失败');
        }
      },
      fail() {
        reject('刷新失败');
      },
    });
  })
}

// 检查登陆session
export const CheckSession = (): Promise<boolean> => {
  return new Promise((resolve) => {
    wx.checkSession({
      success(res) {
        console.log('checkSession1', res)
        if (res.errMsg === 'checkSession:ok') {
          resolve(true)
        } else {
          resolve(false);
        }
      },
      fail() {
        resolve(false); // session过期
      },
    });
  })
}

// 登录(客户端调用接口获取code)
export const Login = async (): Promise<string> => {
  return new Promise((resolve, reject) => {
    wx.login({
      success (res) {
        if (res['errMsg'] === 'login:ok') {
          resolve(res['code'] || '');
        } else {
          reject('登录失败！' + res.errMsg)
        }
      },
      fail() {
        reject('登录错误！');
      }
    })
  });
}

// 获取appId
export const GetAppId = (): Promise<string> => {
  return new Promise((resolve) => {
    const _getAccountInfoSync = wx.getAccountInfoSync();
    const _appId: string = _getAccountInfoSync['miniProgram']['appId'] || '';
    resolve(_appId);
  });
}

/**
 * 选择照片、拍照
 * @param count 最多可以选择的图片数量，拍照时此选项无效
 * @param sourceType 图片来源{album:相册,camera:相机:album&camera：相册相机}
 * @param sizeType 是否选择原图{original:原图,显示并默认勾选原图按钮,compressed:压缩图,不显示原图按钮}
 */
export const ChooseImage = (prop: {
  count: number,
  mediaType: Array<'image' | 'video' | 'mix'>,
  sourceType: Array<'album' | 'camera'>,
  sizeType: string[],
}): Promise<any> => {
  return new Promise((resolve) => {
    wx.chooseMedia({
      count: prop.count,
      mediaType: prop.mediaType,
      sizeType: prop.sizeType,
      sourceType: prop.sourceType,
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        resolve(err);
      }
    });
  })
};
